<template>
    <view class="spoken_exam">
        <!-- 头部 -->
        <div class="head" v-if="!source">
            <!-- <div class="class-list">
                <div class="class-item" v-for="(item, index) in testList" @click="handleClass(index)"
                    :class="{'active':index === partIndex }" :key="index">
                    Q {{ index+1 }}
                </div>
            </div> -->
            <scroll-view v-if="!source" class="class-list scroll-view_H" scroll-x="true" :scroll-left="scrollLeft" :scroll-with-animation="true" :show-scrollbar="false" enhanced="true">
                <div class="class-item" v-for="(item, index) in testList" :key="index" :class="{'active': index === partIndex}" @click="handleClass(index)">
                    Q{{ index+1 }}
                </div>
            </scroll-view>
        </div>
        
        <!-- 题干内容 -->
        <div class="content">
            <div class="test-list">
                <div class="test-item">
                    <div class="title-text">{{ question.topicType }}</div>
                    <div class="time-text">Question {{ partIndex+1 }}/{{ testList.length }} ｜ {{ question.time }}题库</div>
                    <div class="cont-text" v-html="question.topicName"></div>
                </div>
            </div>
        </div>

		<!-- 高分范文 -->
		<div class="good-topic" v-if="question.modelEssay">
			<div class="title">参考答案</div>
			<div class="content-warp" v-show="viewTopicFlag">
				<div class="text" v-html="question.modelEssay"></div>
			</div>
			<div class="show-or-hide" :class="{hide: !viewTopicFlag}" @click="viewTopicFlag = ! viewTopicFlag">
				<span v-show="viewTopicFlag">收起范文</span>
				<span v-show="!viewTopicFlag" @click="handleClick('ViewSampleEssay')">点击查看范文</span>
			</div>
		</div>

        <!-- 答题记录 -->
        <div class="spoken-list">
            <div class="radio-tabs">
                <div class="tab-btn" @click="changeRecordData('other')" :class="{'active': recordActive=='other'}">用户录音</div>
                <div class="tab-btn" @click="changeRecordData('my')" :class="{'active': recordActive=='my'}">我的录音（{{myRecordingTotal}}）</div>
            </div>
        </div>
		<div class="list-box" v-if="recordingList.length">
			<scroll-view :scroll-top="scrollTop"  scroll-y="true" class="scroll-y" @scrolltoupper.stop="backToTop">
				<div class="scroll-bg" >
					<div class="list-data"><!--  <=这层是为了做左滑出现删除的样式调整的 @touchend="ListTouchEnd(item)" -->
						<div :style="{ 'left': showContent&&recordCode==item.recordId?'-114rpx':0 }"  @touchstart="ListTouchStart" @touchmove="ListTouchMove($event,item)"  class="record-list" v-for="(item,index) in recordingList" :key="index">
						<div style="flex: 1;">
							<view class="outer-layer">
								<div class="flex-start">
									<div class="people-img">
										<image v-if="item.avatar" :src="item.avatar"></image>
										<image v-else style="height:1.8rem;width:1.8rem" src='../../static/mine_default_avatar.png'></image>
									</div>
									<div class="sub-info">
										<div class="name">{{item.nickName}}</div>
										<div class="time">{{item.createTime}}</div>
									</div>
									
								</div>
								<div class="switch-right" v-if="recordActive=='my'">
									<span>公开录音</span>
									<div @click="switchEvent(item,index)">
										<image src="../../static/ic_open.png" v-if="item.isPublic"></image>
										<image src="../../static/ic_close.png" v-else></image>
									</div>
									
								</div>
							</view>
							
							<div style="display: flex; justify-content: space-between; align-items: center;">
								<radio-player style="flex: 1;" ref="ref1" :playCode='playCode' @playEvent='playEvent' @click="doPlay" :dataObj="item"></radio-player>
								<div class="audio-right" @click="likedEvent(item,index)">
									<image src="../../static/ic_praise_select.png" v-if="item.isLiked"></image>
									<image src="../../static/ic_praise_default.png" v-else></image>
									<span>{{item.likeCount>999?'999+':item.likeCount}}</span> 
								</div>
							</div>
						</div>

						<div class="closeBtn">
							<div class="close-Box" @click="deleteEvent(item)">
								删除
							</div>
						</div>
					</div>
					</div>
					
				</div>
				<div v-if="noMore" class="noMoreStyle">
						-已经到底了-
				</div>
			</scroll-view>
		</div>
		<div class="nodata" v-if="total==0&&!recordingList.length">
			<img src="https://jxfwpt-p.oss-cn-beijing.aliyuncs.com/words/credit/img_emptyx.png" alt="">
			<text>暂无作答记录</text>
		</div>
		<div class="buttom-recorded" v-if="testList.length">
			<AudioPage :question='question' @submitRecord='submitRecord'></AudioPage>
		</div>
    </view>
</template>

<script>
    import { apiSpokenTopic,apiSpeakingMyRecording ,apiSpeakingAllRecording,apiSpeakingLiked,apiSpeakingPublic,apiSpeakingDelete} from '@/api/exam/exam.js'
    import RadioPlayer from './components/radio-player.vue'
	import AudioPage from './components/audioPage.vue'
	
	import privacyDialog from '@/components/privacy-dialog/privacy-dialog.vue'
	import { buryingPoint } from '@/api/index/index.js'
    export default {
        components: {
            RadioPlayer,AudioPage,privacyDialog
        },
        data() {
            return {
                partIndex: 0,
                question: {
                    audioUrl: null,
                    id: 1,
                    partNum: 1,
                    time: "2023年 9-12 月",
                    topicName: "",
                    topicSeries: "",
                    topicType: "Teachers"
                },
                testList: [],
                scrollLeft: 0,
                recordActive: 'other',
				scrollTop:0,
				pageSize:10,
				pageNum:1,
				recordingList:[],//音频列表数据
				myRecordingTotal:0,//我得音频条数
				listTouchDirection:'',
				touchDataXY:null,
				showContent:false,
				recordCode:null,
				playCode:0,
				total:null,
				source:'',
				noMore:false,
				viewTopicFlag: false

            }
        },
        onLoad(options) {
            this.timeStr = options.timeStr
            this.topicType = decodeURIComponent(options.topicType)
            this.topicSeries = options.topicSeries
            this.partType = options.partType
            this.partIndex = options.index ?  parseInt(options.index) : 0
			this.source= options.page?options.page:''
			// =practice
            this.getInfo()
        },
		onReachBottom(){
			console.log('到底加载更多')
			this.loadMoreData()
		},
        methods: {
			// 埋点
			handleClick(type, remark = ''){
				buryingPoint({type, remark})
			},
			// 删除
			deleteEvent(item){

				apiSpeakingDelete({
					recordId:item.recordId
				}).then((res)=>{
					console.log('删除成功',res)
					this.recordingList=[]
					this.scrollTop=0
					this.pageNum = 1;
					if(this.recordActive=='my'){
						// 获取我得录音
						this.speakingMyRecording(this.question)
					}
				})
			},
			// 发布音频
			submitRecord(){
				this.recordActive='my'
				this.recordingList=[]
				this.scrollTop=0
				this.pageNum = 1;
				this.speakingMyRecording(this.question)
				

			},
			playEvent(item){
				console.log('播放',item)
				this.playCode=item
			},
			// 是否公开录音
			switchEvent(item,index){
				this.recordingList[index].isPublic=!this.recordingList[index].isPublic
				apiSpeakingPublic({
					recordId:item.recordId,
					isPublic:this.recordingList[index].isPublic
				}).then(res=>{
					console.log('是否公开音频返回结果',res)
				
				}).catch(error=>{
					this.$tip.confirm(error.msg, false)
				})
			},
			// 点赞
			likedEvent(item,index){
				this.recordingList[index].isLiked=!this.recordingList[index].isLiked
				if(this.recordingList[index].isLiked){
					this.recordingList[index].likeCount+=1
				}else{
					this.recordingList[index].likeCount-=1
				}
				apiSpeakingLiked({
					recordId:item.recordId
				}).then(res=>{
					console.log('点赞接口',res)
				}).catch(error=>{
					this.$tip.confirm(error.msg, false)
				})
			},
            // 切换题目
            handleClass(index)  {
				this.playCode=0
				this.showContent = false;
				this.scrollTop=0
				this.pageNum=1
				this.noMore=false
				this.recordingList=[]
				this.recordActive='other'
				this.viewTopicFlag = false
				// 获取我得录音
				// this.speakingMyRecording(this.question)
				// // 获取公共录音
				// this.speakingAllRecording(this.question)
				
				if(!this.source){
					this.$nextTick(() => {
						// 获取taglist的宽度
						const wquery = wx.createSelectorQuery().in(this);
						wquery.select('.class-list').boundingClientRect((rect) => {
						  this.scrollViewWidth = rect.width
						}).exec();
						
						// 获取单个tag的内容
						const query = wx.createSelectorQuery().in(this);
						query.selectAll('.class-item').boundingClientRect((rects) => {
						  const selectedRect = rects[index];
						  const currentIndexWidth = selectedRect.width  ? selectedRect.width * index : 51 * index
						  const scrollLeft = currentIndexWidth - (this.scrollViewWidth - selectedRect.width) / 2;
						  this.scrollLeft = scrollLeft > 0 ? scrollLeft : 0
						}).exec();
					})
				}
                
                this.partIndex = index
                this.question = this.testList[index]
				console.log('this.question', this.question)
				// 获取我得录音
				this.speakingMyRecording(this.testList[index])
				// 获取公共录音
				this.speakingAllRecording(this.testList[index])
                wx.setNavigationBarTitle({
                    title: '口语 Part' + this.question.partNum 
                })
            },
            // 获取题目列表数据
            getInfo() {
                apiSpokenTopic({
                    timeStr: this.timeStr,
                    topicType: this.topicType,
                    topicSeries: this.topicSeries,
                    partType: this.partType
                }).then(res => {
                    this.testList = res.data
					console.log('this.testList', this.partIndex,res.data)
					this.handleClass(this.partIndex)

                })
            },
            // 切换录音数据
            changeRecordData(type) {
                this.recordActive = type
				this.playCode=0
				this.showContent = false;
				this.recordingList=[]
				this.scrollTop=0
				this.pageNum=1
				this.noMore=false
				console.log('切换不好使么',type,this.question)
				if(type=='my'){
					// 获取我得录音
					this.speakingMyRecording(this.question)
				}else{
					// 获取公共录音
					this.speakingAllRecording(this.question)
				}
            },
            // 播放音频
            doPlay() {
                console.log('sssd')
            },
			// 获取我得录音
			speakingMyRecording(item){
				console.log('走了么',item)
				this.$tip.loading()
				apiSpeakingMyRecording({
					topicId:item.id,
					pageSize:this.pageSize,
					pageNum:this.pageNum
				}).then(res=>{
					console.log('我的录音',res)
					this.$tip.loaded()
					if(res.code==200){
						this.myRecordingTotal=res.data.total
						
						if( this.recordActive=='my'){
							this.total=res.data.total
							this.recordingList.push(...res.data.rows)  
							this.noMore = this.total <= this.recordingList.length
						}
					
					}else{
						this.$tip.confirm(res.msg, false)
					}
					 
				}).catch(err=>{
					this.$tip.confirm(err.msg, false)
					this.$tip.loaded()
				})
			},
			// 公开的所有录音
			speakingAllRecording(item){
				this.$tip.loading()
				apiSpeakingAllRecording({
					topicId:item.id,
					pageSize:this.pageSize,
					pageNum:this.pageNum
				}).then(res=>{
					 this.$tip.loaded()
					if(res.code==200){
						this.total=res.data.total
						this.recordingList.push(...res.data.rows ) 
						this.noMore = this.total <= this.recordingList.length
						// this.recordingList[0].likeCount=99
					}else{
						this.$tip.confirm(res.msg, false)
					}
				}).catch(err=>{
					this.$tip.loaded()
					this.$tip.confirm(err.msg, false)
				})
			},
			backToTop() {
					
				this.scrollTop=0
					
			},
			// 进入详情
			scroll(e){
					this.scrollTop=e.detail.scrollTop
					// uni.navigateTo({
					// 	url: "pages/words/address?orderNumber="+item.orderNumber
					// })
			},
			loadMoreData(){
					if(!this.noMore){
						this.pageNum += 1;
						if(this.recordActive=='my'){
							// 获取我得录音
							this.speakingMyRecording(this.question)
						}else{
							// 获取公共录音
							this.speakingAllRecording(this.question)
						}
					}
			},
			// 删除简单词操作
			ListTouchStart(e,index){ // ListTouch触摸开始
				// this.listTouchStart = e.touches[0].pageX; //当前手指在屏幕的位置
				this.touchDataXY = {
					startX: e.changedTouches[0].clientX,
					startY: e.changedTouches[0].clientY,
				}
			},
			ListTouchMove(e,item) { // ListTouch计算方向   手指最后在屏幕的位置小于首次手指在屏幕的位置则向左滑动
			let startX = this.touchDataXY.startX //按下的X轴
			let startY = this.touchDataXY.startY	//按下的Y轴
			let touchMoveX = e.changedTouches[0].clientX; //滑动变化X坐标
			let touchMoveY = e.changedTouches[0].clientY; //滑动变化Y坐标
			let angle = this.angle({
				 X: startX,
				 Y: startY
			 }, {
				 X: touchMoveX,
				 Y: touchMoveY
			 });
			if (Math.abs(angle) > 30) return;
			   this.listTouchDirection = touchMoveX > startX ? 'right' : 'left'
			   this.ListTouchEnd(item)
			},
			ListTouchEnd(item){
				// if(this.flag == 2){
					if (this.listTouchDirection == 'left'&&this.recordActive=='my') { 
						this.recordCode=item.recordId
						this.showContent = true;
					} else{
						this.showContent = false;
						this.recordCode=''
					}
					this.listTouchDirection = null	
				// }		
			},
			 /**
			 * 计算滑动角度
			 * @param {Object} start 起点坐标
			 * @param {Object} end 终点坐标
			 */
			angle(start, end) {
			 var _X = end.X - start.X,
			 _Y = end.Y - start.Y
			 //返回角度 /Math.atan()返回数字的反正切值
			 return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
			},
			
        }
    }
</script>
<style>
    Page {
        background-color: #F6F8FC;
    }
</style>
<style scoped lang="scss">
    @function torem($rpx){  //$rpx为需要转换的字号
        @return #{$rpx * 100 / 750 / 4}rem; 
    }
    .spoken_exam{
		height: 100%;
		width: 100%;
		display: flex;
		flex-direction: column;
		min-height: 100%;
		// overflow: auto;
	}
    .head {
        background-color: #ffffff;
        .class-list {
            width: calc(100% - 1.8rpx);
            overflow-y: hidden;
            overflow-x: scroll;
            transition: left 0.2s ease-out;
            height: torem(64);
            line-height: torem(64);
            font-size: torem(28);
            margin-top: torem(10);
            padding-bottom: torem(14);

            .class-item {
                padding: 0 torem(30);
                color: #999999;
                position: relative;
                text-align: center;
                display: inline-block;
            }
            
            

            .active {
                color: #333333;
                font-weight: bold;
                font-size: torem(28);
            }

            .active::before {
                position: absolute;
                left: calc(50% - 0.6rem);
                text-align: center;
                bottom: torem(4);
                content: ' ';
                width: torem(36);
                height: torem(6);
                line-height: torem(6);
                background: #FD453D;
                border-radius: torem(3);
            }
        }

    }
    .content {
        padding: torem(30) torem(30);
        background-color: #F6F8FC;
        .test-list {
            .test-item {
                background: #FFFFFF;
                border-radius: torem(10);
                display: flex;
                flex-direction: column;
                justify-content: center;
                padding: torem(20) torem(20);
                .title-text {
                    font-size: torem(28);
                    font-weight: 600;
                    color: #333333;
                }
                .time-text {
                    font-size: torem(24);
                    font-weight: 400;
                    color: #999999;
                }
                .cont-text {
                    font-size: torem(28);
                    font-weight: 400;
                    color: #333333;
                    overflow: hidden;
                    // white-space: nowrap;
                    // text-overflow: ellipsis;
                }
            }
        }
    }
	.good-topic{
		font-size: torem(28);
		color: #333;
		margin: 0 torem(30) torem(34);
		.title{
			color: #999;
			margin-bottom: torem(20);
		}
		.content-warp{
			background-color: #fff;
			border-radius: torem(10) torem(10) 0 0;
			padding: torem(28) torem(24) 0;
			.text{
				line-height: torem(40);
				border-bottom: 1rpx solid #ECECEC;
				box-sizing: border-box;
				padding-bottom: torem(30);
			}
			
		}
		.show-or-hide{
			width: 100%;
			height: torem(80);
			color: #999;
			font-size: torem(24);
			text-align: center;
			line-height: torem(80);
			background-color: #fff;
			border-radius: 0 0 torem(10) torem(10);

		}
		.hide{
			background-color: #E7EEFF;
			border: 1rpx solid #4F7DEF;
			border-radius: torem(10);
			color: #2F56E5;
		}
	}

    
    
    .spoken-list {
        padding: 0 torem(30) torem(0) torem(30);
		.radio-tabs {
		    height: torem(40);
		    line-height: torem(40);
		    display: flex;
		    align-items: center;
		    padding-bottom: torem(30);
		    .tab-btn {
		        height: torem(48);
		        line-height: torem(48);
		        border-radius: torem(24);
		        font-size: torem(24);
		        color: #333333;
		        padding: 0 torem(24);
		        margin-right: torem(20);
				background-color: #ffffff;
		    }
		    .active {
		        color: #FFFFFF;
		        background-color: #FD453D;
		    }
		}
	}
	.nodata{
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-bottom: torem(200);
		img{
			width: torem(280);
			height: torem(142);
		}
		text{
			font-size: torem(28);
			font-family: PingFang SC;
			color: #999999;
			
		}
		
	}
    .list-box {
		position: relative;
		flex: 1;
		padding-bottom: torem(180);
		.scroll-bg{
			 padding: 0 torem(30) torem(0) torem(30);
		}
		.noMoreStyle{
			font-size: torem(24);
			color:#ccc;
			display: flex;
			justify-content: center;
			align-items: center;
			padding:torem(15) 0 torem(28);
			// position: absolute;
			width: 100%;
		}
		.list-data{
			 overflow: hidden;
		}
		.record-list:last-child{
			border-bottom: none;
		}
        .record-list {
            background-color: #ffffff;
			padding: torem(35) torem(20);
			position: relative;
			display: flex;
			left: 0;
			transition: left 0.1s ease-out;
			border-bottom: 1px dashed #ECECEC;
			
			.closeBtn{
				background-color: #ffffff;
				height: 100%;
				width: torem(114);
				position: absolute;
				right: torem(-114);
				top: 0;
				display: flex;
				align-items: center;
				.close-Box{
					background-color: #FC5D64;
					width: torem(114);
					height:torem(191);
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: torem(28);
					color: #ffffff;
					border-radius: 15rpx 0rpx 0rpx 15rpx;
				}
			}
            .people-img {
                width: torem(70);
                height: torem(70);
                background-color: #EAEEF6;
                display: flex;
                align-items: center;
                justify-content: center;
				border-radius: 50%;
                image {
                    width: 100%;
                    height: 100%;
					border-radius: 50%;
                }
            }
            .sub-info {
                padding-left: torem(20);
                .name {
                    font-size: torem(28);
                    color: #333333;
                }
                .time {
                    font-size: torem(24);
                    color: #999999;
                }
            }
			
        }
		.outer-layer{
			display: flex;
			justify-content: space-between;
			.switch-right{

				display: flex;
				justify-content: center;
				align-items: center;
				image{
					width:  torem(48);
					height:  torem(28);
				}
				span{
					color: #999999;
					font-size: torem(24);
					padding-right: torem(15);
				}
			}
		}
        .audio-right{
            width: 30px;
            text-align: right;
            font-size: torem(24);
			margin-top: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-left: torem(15);
            image {
                // margin-right: torem(6);
                width: torem(29);
                height: torem(28);
            }
			span{
				padding-top: torem(5);
				min-width: torem(29);
				display: flex;
				justify-content: center;
			}
        }
    }

    .flex-start {
        display: flex;
        align-items: center;
        justify-content: start;
    }
    
    .scroll-Y {
        height: 50rpx;
    }
    .scroll-view_H {
        white-space: nowrap;
        width: 100%;
    }
	.buttom-recorded{
		position: fixed;
		left: 50%;
		margin-left:torem(-61);
		bottom: 0;
		padding-bottom: torem(60);
	}
	

</style>
